<template>
  <div class="app-container">
    <div v-if="showSearch" class="search-container">
      <CommonSearch
        :formConfig="searchColumns"
        :inline="true"
        labelWidth="63px"
        formItemWidth="auto"
        :model="initParam"
      >
        <template #after>
          <el-button type="primary" @click="searchTable">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="resetParam">
            <i-ep-refresh />
            重置
          </el-button>
        </template>
      </CommonSearch>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          :disabled="tableData.length === 0"
          @click="
            useDownload(
              'mes/mesproducetransferform/forwardTraceabilityExport',
              '产品反向追溯查询',
              initParam
            )
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
      </template>
      <!-- 表格主体 -->
      <div v-show="showTable">
        <!-- <el-table
          ref="dataTableRef"
          v-loading="loading"
          v-bind="$attrs"
          :data="tableData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
          @sort-change="onTableSortChanged"
        >
          -- <el-table-column type="selection" width="55" align="center" /> -->
        <!-- 表格内容操作 -->
        <!-- <template v-for="item in tableColumns" :key="item">
            <TableColumn v-if="item.prop && item.isShow" :column="item">
              <template v-for="slot in Object.keys($slots)" #[slot]="scope">
                <slot :name="slot" v-bind="scope"></slot>
              </template>
            </TableColumn>
          </template>
        </el-table> -->

        <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="tableData"
          highlight-current-row
          default-expand-all
          border
          @selection-change="handleSelectionChange"
          row-key="id"
          :tree-props="{
            children: 'children',
            hasChildren: 'hasChildren',
          }"
        >
          <el-table-column
            prop="plantCode"
            label="工厂"
            align="left"
            width="100"
            type=""
          />
          <el-table-column
            prop="workCenterCode"
            label="工作中心"
            minWidth="260"
            align="left"
            type=""
          >
            <template #default="{ row }">
              <span>{{ row.workCenterCode }}-{{ row.workCenterName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="materialCode"
            label="物料编码"
            minWidth="300"
            align="left"
          >
            <template #default="{ row }">
              <span>{{ row.materialCode }}-{{ row.materialName }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="processName"
            label="工序"
            minWidth="180"
            align="left"
          ></el-table-column>
          <el-table-column
            prop="produceTransferFormCode"
            label="工序流转单"
            minWidth="180"
            align="left"
          ></el-table-column>
          <el-table-column
            prop="producePlanCode"
            label="生产计划"
            minWidth="180"
            align="left"
          ></el-table-column>
          <el-table-column
            prop="workOrderCode"
            label="加工单号"
            minWidth="180"
            align="left"
          ></el-table-column>
          <el-table-column
            prop="planBatch"
            label="批次号"
            minWidth="180"
            align="left"
          ></el-table-column>
          <el-table-column
            prop="productQuantity"
            label="数量"
            minWidth="100"
            header-align="center"
            align="right"
          ></el-table-column>
          <el-table-column prop="quantityUnit" label="数量单位" align="left">
            <template #default="{ row }">
              <span>{{
                useDictionary("MeasurementUnit", row.quantityUnit)
              }}</span>
            </template></el-table-column
          >
          <el-table-column
            prop="completeTime"
            label="加工日期"
            minWidth="150"
            align="center"
          >
            <template #default="{ row }">
              <span>{{ row.completeTime?.split(" ")[0] }}</span>
            </template></el-table-column
          >
        </el-table>

        <!-- <el-pagination
          :background="true"
          :current-page="pageable.pageNum"
          :page-size="pageable.pageSize"
          :page-sizes="[10, 25, 50, 100]"
          :total="pageable.total"
          layout="total, sizes, prev, pager, next, jumper"
          class="mt-[20px]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        /> -->
      </div>
    </el-card>

    <!-- 列设置 抽屉组件 -->
    <!-- <ColSetting
      v-model:col-setting="tableColumns"
      v-model:search-setting="searchColumns"
      @search-handle="(e:boolean) => (showSearch = e)"
      @col-handle="(e:boolean) => (showTable = e)"
    /> -->
  </div>
</template>

<script setup lang="tsx">
import { useTable, useDictionary, useDownload } from "@/utils/useTable";
import { filterOrder } from "@/utils/commonHooks";
import {
  getPlantList,
  getWorkShopList,
  getMaterials,
} from "@/utils/commonData";
import { getMesprocessList } from "@/api/andon/andon";
import request from "@/utils/request";

defineOptions({
  name: "STATISTICALQUERYPRODUCTTRACEABILITYREVERSE",
  inheritAttrs: false,
});

/** 自定义设置方法   start **/

const resetParam = () => {
  initParam.externalCode = "";
  tableData.value = [];
};
// 搜索参数 设置为响应式
const searchColumns: any = reactive([
  {
    type: "input", // 普通输入框
    isShow: true,
    inputType: "text", // 类型, text/textarea
    label: "包装条码", // 标签文本
    fieldName: "externalCode", // 字段名称
    placeholder: "请输入包装条码", // 提示文字
    initValue: "", // 默认值
  },
]);

// 接收 columns 并设置为响应式
const tableColumns = reactive([
  {
    prop: "plantCode",
    label: "工厂",
    isShow: true,
    width: 100,
    render: (scope: any) => <span>{scope.row?.plantCode ?? ""}</span>,
  },
  {
    prop: "workCenterCode",
    label: "工作中心",
    isShow: true,
    minWidth: 180,
    render: (scope: any) => (
      <span>{`${scope.row.workCenterCode ?? ""}-${
        scope.row.workCenterName ?? ""
      }`}</span>
    ),
  },
  {
    prop: "materialCode",
    label: "物料",
    isShow: true,
    minWidth: 180,
    render: (scope: any) => (
      <span>{`${scope.row.materialCode ?? ""}-${
        scope.row.materialName ?? ""
      }`}</span>
    ),
  },
  {
    prop: "processName",
    label: "工序",
    isShow: true,
    minWidth: 100,
    render: (scope: any) => <span>{scope.row?.processName ?? ""}</span>,
  },
  {
    prop: "produceTransferFormCode",
    label: "工序流转单",
    isShow: true,
    minWidth: 180,
  },
  { prop: "producePlanCode", label: "生产计划", isShow: true, minWidth: 100 },
  { prop: "workOrderCode", label: "加工单号", isShow: true, minWidth: 100 },
  { prop: "produceBatch", label: "批次号", isShow: true, minWidth: 100 },
  {
    prop: "productQuantity",
    label: "数量",
    isShow: true,
    minWidth: 100,
    align: "right",
  },
  { prop: "quantityUnit", label: "数量单位", isShow: true, minWidth: 100 },
  {
    prop: "completeTime",
    label: "加工日期",
    isShow: true,
    minWidth: 150,
    render: (scope: any) => <span>{scope.row.completeTime?.split(" ")}</span>,
  },
]);

// 是否显示搜索框
const showSearch = ref(true);

// 是否table
const showTable = ref(true);

/** 列表项自定义方法   end **/

// 请求参数
const requestApi = "mes/mesproducetransferform/forwardTraceabilityQuery";

// 是否需要分页
const pagination = true;

// 初始化搜索参数数据
const searchParamInit = {};
const initParam = reactive({ searchFlag: "2", externalCode: "" });
// 数据请求错误后处理
function requestError() {}

// 数据请求错误后处理
// function dataCallBack() {}   //需要处理
const dataCallBack = ref(undefined); //无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError
);

// 如果初始化表格需要排序=》const initParam = reactive({sort:''});
// 监听页面 initParam 改化，重新获取表格数据
// watch(() => initParam, getTableList, { deep: true });
onMounted(async () => {
  getSelectPlantList();
});

// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}

// 获取工厂列表
async function getSelectPlantList() {
  const list = (await getPlantList()) ?? [];
  list?.map((item) => {
    item.label = `${item.organizationCode}`;
    item.value = `${item.id}`;
  });
  searchColumns[0].optionList = list;
}

// 工厂选择
async function selectPlant(e: string) {
  if (e) {
    // 获取工作中心列表
    const list = (await getWorkShopList(e)) ?? [];
    list?.map((item) => {
      item.label = `${item.workshopCode}-${item.workshopName}`;
      item.value = `${item.id}`;
    });
    searchColumns[1].optionList = list;
    searchParam.value.workCenterId = "";
    searchColumns[2].optionList = [];
    searchParam.value.processId = "";
    searchColumns[3].optionList = [];
    searchParam.value.materialCode = "";
  } else {
    searchColumns[1].optionList = [];
    searchParam.value.workCenterId = "";
    searchColumns[2].optionList = [];
    searchParam.value.processId = "";
    searchColumns[3].optionList = [];
    searchParam.value.materialCode = "";
  }
}

// 工作中心选择
function selectWorkCenter(e: any) {
  if (e) {
    getProcessList(e);
    getMaterialList();
  } else {
    searchColumns[2].optionList = [];
    searchParam.value.processId = "";
    searchColumns[3].optionList = [];
    searchParam.value.materialCode = "";
  }
}

// 加工时间选择
function getRequestTime(data: any) {
  if (data) {
    searchParam.value.requestTimeStart = data[0];
    searchParam.value.requestTimeEnd = data[1];
  } else {
    searchParam.value.requestTimeStart = "";
    searchParam.value.requestTimeEnd = "";
  }
}

// 工序列表获取
async function getProcessList(id) {
  const { data } = await getMesprocessList({ workCenterId: id, enabled: 1 });
  data?.forEach((item) => {
    item.label = `${item.processCode}-${item.processName}`;
    item.value = `${item.id}`;
  });
  searchColumns[2].optionList = data;
}

// 物料列表获取
async function getMaterialList() {
  const list = await getMaterials(
    searchParam.value.plantId,
    searchParam.value.workCenterId
  );
  list?.forEach((item) => {
    item.label = `${item.materialCode}-${item.materialName}`;
    item.value = `${item.materialCode}`;
  });
  searchColumns[3].optionList = list;
}

// 重置数据处理
function handleReset() {
  reset();
  getSelectPlantList();
  searchColumns[1].optionList = [];
  searchColumns[2].optionList = [];
  searchColumns[3].optionList = [];
}
const searchTable = () => {
  console.log(initParam);

  if (!initParam.externalCode) {
    ElMessage.error("请输入包装条码");
    return;
  }
  getTableList();
};
</script>
